package com.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 一个线程启动很久，采用中断机制
public class JUC_ReentrantLock_interruptibly_16 {

    public static void main(String[] args) {
        Lock lock = new ReentrantLock(true);//设置true 线程锁公平竞争

        new Thread(()->{
            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName()+" invoked...start");
                TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
                System.out.println(Thread.currentThread().getName()+"invoked...end");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        },"t1").start();

        Thread t2 = new Thread(()->{
            try {
                //lock.lock();
                System.out.println(Thread.currentThread().getName()+" invoked...start");
                lock.lockInterruptibly();
                TimeUnit.SECONDS.sleep(5);
                System.out.println(Thread.currentThread().getName()+" invoked...end");
            } catch (InterruptedException e) {
                System.out.println("t2 interrupted");
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        },"t2");

        t2.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t2.interrupt();//打断线程2的等待
    }
}

